package com.manli.api.util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.manli.api.enums.AuthEnums;
import com.manli.api.pojo.SessionInfo;

import io.jsonwebtoken.Claims;
/**
 * 获取sessionInfo
 * @author Shensg
 *
 * 2020年5月3日
 */
@Component
public class SessionInfoUtils {
	
	@Autowired
    private RedisUtil redisUtil;
	/**
	 * 集成session 和 jwt token 获取用户信息
	 * session 
	 * 		key sessionInfo
	 * 		过期时间 在启动类注解上上已经设置
	 * jwt token
	 * 		key sessionInfo:userId+
	 * @param request
	 * @return
	 */
	public SessionInfo getSessionInfoByAuth(HttpServletRequest request) {
		String authToken = request.getHeader(AuthEnums.Auth_TOKEN.getContent());
		String authTokenWECHAT = request.getHeader(AuthEnums.Auth_TOKEN_WECHAT.getContent());
		SessionInfo sessionInfo = null;
		//如果有auth_token走的是jwttoken校验
		if(authToken!=null && !"".equals(authToken)) {//后台登陆
			Claims claims = JwtUtils.verifyJwt(authToken);
			if (claims!=null) {
				String userId = claims.get("userId").toString();
				String name = claims.get("userName").toString();
				if (redisUtil.hasKey("auth_token:"+userId+":"+name)) {
					sessionInfo = (SessionInfo)redisUtil.get("auth_token:"+userId+":"+name);
				}
			}
		}else if(authTokenWECHAT!=null && !"".equals(authTokenWECHAT)) {//微信端登陆
			Claims claims = JwtUtils.verifyJwt(authTokenWECHAT);
			if (claims!=null) {
				String openid = claims.get("openid").toString();
				if (redisUtil.hasKey("auth_token_wechat:"+openid)) {
					sessionInfo = (SessionInfo)redisUtil.get("auth_token_wechat:"+openid);
				}
			}
		}else {
			HttpSession session = request.getSession();
			sessionInfo = (SessionInfo) session.getAttribute(AuthEnums.AUTH_SESSION.getContent());
		}
		return sessionInfo;
	}
}
